// pages/personal/newAddress/newAddress.js
import { newAddress, updateDefault, deleteAddress, updateAddress, queryTreeAll, listByParentCode } from '../../../../config/config'
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '新增',
    setDefault: false,
    isAdd: true,
    control: true,
    memberId:	'', // 用户id
    name:	'', // 收货人名称
    phoneNumber: '', // 收货人电话号码
    // provinceArray:[], // 全部省
    // cityArray:[], // 市
    // areaArray:[], // 区
    // streetArray:[], // 街道
    // multiArray: [], // 选中的省市区
    // multiIndex: [0, 0, 0, 0],
    // provinceCode: '',
    // cityCode: '',
    // areaCode: '',
    // streetCode: '',
    // region: '',  // 地区完整名
    detailAddress:	'', // 详细地址
    titleHeight: '',
    showOtherAddr:false,
    showAddress: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (res) {
    let that = this
    wx.getSystemInfo({
      success (res) {
        let statusBarHeight = res.statusBarHeight + 65
        console.log(statusBarHeight)
        that.setData({
          titleHeight: statusBarHeight + 'px'
        })
      }
    })

    if(res.option) {
      let option = JSON.parse(res.option)
      console.log('option', option)
      if (option.defaultStatus == 'N') {
        that.setData({
          setDefault: false
        })
      } else {
        that.setData({
          setDefault: true
        })
      }
      that.setData({
        isAdd: false,
        control: false,
        title: '编辑',
        id: option.id,
        name: option.name,
        phoneNumber: option.phoneNumber,
        detailAddress: option.detailAddress,
        sprovince: {areaLevel: '2', code: option.province, name: option.provinceName},
        scity: {areaLevel: '3', code: option.city, name: option.cityName},
        sregion: {areaLevel: '4', code: option.region, name: option.regionName},
        sstreetName: {areaLevel: '5', code: option.street, name: option.streetName},
        showAddress: option.provinceName + option.cityName + option.regionName + option.streetName
      })
      let parms = {parentCode:option.region}
      app.reqFun.requestJson('get',listByParentCode,parms,(res)=>{
        if(res.data.success == 1){ 
          that.setData({
            itemsAddr: res.data.data,      
          })
        }else{
          wx.showToast({
            title: '查询地址失败：'+res.data.msg,
            icon:'none'
          })
        }
      },true)
      // that.getAddressSelectData(code, 'edit')
      // that.queryTreeAll()
    } else {
      // that.queryTreeAll()
    }
  },
  setDefaultChange({ detail }) {
    this.setData({
      setDefault: detail
    });
    if (!this.data.isAdd) {
      this.updateDefaultStatus()
    }
  },
  backSpace() {
    wx.navigateBack({
      delta: 1
    })
  },
  nameInput: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  phoneNumberInput: function (e) {
    this.setData({
      phoneNumber: e.detail.value
    })
    if (!(/^1[345678]\d{9}$/.test(e.detail.value))) {
      wx.showToast({
      title: '手机号码有误',
      duration: 2000,
      icon:'none'
      });
    }
  },
  detailAddressInput: function (e) {
    this.setData({
      detailAddress: e.detail.value
    })
  },
  // 获取省
  // queryTreeAll() {
  //   let control = this.data.control
  //   app.reqFun.requestJson('GET',queryTreeAll,'',(res)=>{
  //     if(res.data.success==1){
  //       let data = res.data.data
  //       let region = this.data.region
  //       let multiIndex = this.data.multiIndex
  //       let provinceCode = this.data.provinceCode
  //       let multiArray = []
  //       let provinceArray = []
  //       for (let i = 0, len = data.length; i < len; i++){
  //         provinceArray.push(data[i].name)
  //         if (provinceCode == data[i].code) {
  //           region = data[i].name
  //           multiIndex[0] = i
  //         }
  //       }
  //       multiArray[0] = provinceArray
  //       this.setData({
  //         provinceArray: data,
  //         multiArray: multiArray
  //       })
  //       if (!control) {
  //         this.setData({
  //           region: region,
  //           multiIndex: multiIndex
  //         })
  //         this.getCity(provinceCode)
  //       } else {
  //         this.getCity(data[0].code)
  //       }
  //     }
  //   })
  // },
  // 获取市
  // getCity(code) {
  //   let control = this.data.control
  //   let listByParentCodeUrl = listByParentCode + '?parentCode=' + code
  //   app.reqFun.requestJson('GET',listByParentCodeUrl,'',(res)=>{
  //     if(res.data.success==1){
  //       let data = res.data.data
  //       let multiArray = this.data.multiArray
  //       let multiIndex = this.data.multiIndex
  //       let cityCode = this.data.cityCode
  //       let region = this.data.region
  //       let cityArray = []
  //        for (let j = 0, len = data.length; j < len; j++){
  //         cityArray.push(data[j].name)
  //         if (cityCode == data[j].code) {
  //           region = region + '、' + data[j].name
  //           multiIndex[1] = j
  //         }
  //       }
  //       multiArray[1] = cityArray
  //       this.setData({
  //         cityArray: data,
  //         multiArray: multiArray
  //       })
  //       if (!control) {
  //         this.setData({
  //           region: region,
  //           multiIndex: multiIndex
  //         })
  //         this.getArea( cityCode)
  //       } else {
  //         this.getArea(data[0].code)
  //       }
  //     }
  //   })
  // },
  // 获取区
  // getArea(code) {
  //   let control = this.data.control
  //   let listByParentCodeUrl = listByParentCode + '?parentCode=' + code
  //   app.reqFun.requestJson('GET',listByParentCodeUrl,'',(res)=>{
  //     if(res.data.success==1){
  //       let data = res.data.data
  //       let multiArray = this.data.multiArray
  //       let multiIndex = this.data.multiIndex
  //       let areaCode = this.data.areaCode
  //       let region = this.data.region
  //       let areaArray = []
  //        for (let k = 0, len = data.length; k < len; k++){
  //         areaArray.push(data[k].name)
  //         if (areaCode == data[k].code) {
  //           region = region + '、' + data[k].name
  //           multiIndex[2] = k
  //         }
  //       }
  //        multiArray[2] = areaArray
  //        this.setData({
  //         areaArray: data,
  //         multiArray: multiArray
  //       })
  //       if (!control) {
  //         this.setData({
  //           region: region,
  //           multiIndex: multiIndex
  //         })
  //         this.getStreet(areaCode)
  //       } else {
  //         this.getStreet(data[0].code)
  //       }
  //     }
  //   })
  // },
  // 获取街道
  // getStreet(code) {
  //   let control = this.data.control
  //   let listByParentCodeUrl = listByParentCode + '?parentCode=' + code
  //   app.reqFun.requestJson('GET',listByParentCodeUrl,'',(res)=>{
  //     if(res.data.success==1){
  //       let data = res.data.data
  //       let multiArray = this.data.multiArray
  //       let multiIndex = this.data.multiIndex
  //       let streetCode = this.data.streetCode
  //       let region = this.data.region
  //       let streetArray = []
  //        for (let k = 0, len = data.length; k < len; k++){
  //         streetArray.push(data[k].name)
  //         if (streetCode == data[k].code) {
  //           region = region + '、' + data[k].name
  //           multiIndex[3] = k
  //         }
  //       }
  //        multiArray[3] = streetArray
  //        this.setData({
  //         streetArray: data,
  //         multiArray: multiArray,
  //       })
  //       if (!control) {
  //         this.setData({
  //           region: region,
  //           multiIndex: multiIndex
  //         })
  //       }
  //     }
  //   })
  // },
  // 选择省市区
  // multiPickerColumnChange: function (e) {
  //   let that = this
  //   let column = e.detail.column
  //   let value = e.detail.value
  //   let provinceArray = that.data.provinceArray
  //   let cityArray = that.data.cityArray
  //   let areaArray = that.data.areaArray
  //   let provinceCode = ''
  //   let cityCode = ''
  //   let areaCode = ''
  //   that.setData({
  //     control: true
  //   })
  //   if (column === 0) {
  //     for (let i = 0, len = provinceArray.length; i < len; i++){
  //       if(value == i) {
  //         provinceCode = provinceArray[i].code
  //       }
  //     }
  //     that.getCity(provinceCode)
  //   } else if (column === 1) {
  //     for (let i = 0, len = cityArray.length; i < len; i++){
  //       if(value == i) {
  //         cityCode = cityArray[i].code
  //       }
  //     }
  //     that.getArea(cityCode)
  //   } else if (column === 2) {
  //     for (let i = 0, len = areaArray.length; i < len; i++){
  //       if(value == i) {
  //         areaCode = areaArray[i].code
  //       }
  //     }
  //     that.getStreet(areaCode)
  //   }
  // },
  // 选择确认省市区
  // bindMultiPickerChange: function (e) {
  //   console.log('e', e)
  //   let that = this
  //   let multiIndex = e.detail.value
  //   let provinceArray = that.data.provinceArray
  //   let cityArray = that.data.cityArray
  //   let areaArray = that.data.areaArray
  //   let streetArray = that.data.streetArray
  //   let provinceCode = ''
  //   let cityCode = ''
  //   let areaCode = ''
  //   let streetCode = ''
  //   let provinceName = ''
  //   let cityName = ''
  //   let areaName = ''
  //   let streetName = ''
  //   for (let i = 0, len = provinceArray.length; i < len; i++){
  //     if(multiIndex[0] == i) {
  //       provinceName = provinceArray[i].name
  //       provinceCode = provinceArray[i].code
  //     }
  //   }
  //   for (let j = 0, len1 = cityArray.length; j < len1; j++){
  //     if(multiIndex[1] == j) {
  //       cityName = cityArray[j].name
  //       cityCode = cityArray[j].code
  //     }
  //   }
  //   for (let k = 0, len2 = areaArray.length; k < len2; k++){
  //     if(multiIndex[2] == k) {
  //       areaName = areaArray[k].name
  //       areaCode = areaArray[k].code
  //     }
  //   }
  //   for (let l = 0, len3 = streetArray.length; l < len3; l++){
  //     if(multiIndex[3] == l) {
  //       streetName = streetArray[l].name
  //       streetCode = streetArray[l].code
  //     }
  //   }
  //   let region = provinceName + '、' + cityName + '、' +  areaName + '、' +  streetName
  //   console.log('region', region)
  //   that.setData({
  //     multiIndex: multiIndex,
  //     region: region,
  //     provinceCode: provinceCode,
  //     cityCode: cityCode,
  //     areaCode: areaCode,
  //     streetCode: streetCode
  //   })
  // },
  // 点击pickerClick
  pickerClick(e) {
    console.log('点击', e)
  },
  saveAddress() {
    if (this.data.isAdd) {
      this.newAddress()
    } else {
      this.updateAddress()
    }
  },
  // 保存新增地址
  newAddress() {
    let that = this
    let sprovince = that.data.sprovince
    let scity = that.data.scity
    let sregion = that.data.sregion
    let sstreetName = that.data.sstreetName
    let defaultStatus
    let setDefault = that.data.setDefault
    if(setDefault) {
      defaultStatus = 'Y'
    } else {
      defaultStatus = 'N'
    }
    let params = {
      'city':	scity.code,
      'defaultStatus':	defaultStatus,
      'detailAddress':	that.data.detailAddress,
      'memberId':	'',
      'name':	that.data.name,
      'phoneNumber': that.data.phoneNumber,
      'postCode':	'',
      'province': sprovince.code,
      'region': sregion.code,
      'street': sstreetName.code,
    }
    if (!params.name) {
      wx.showToast({
        title: '请填写收货人',
        icon: 'none',
        duration: 3000
      })
    } else if (!params.phoneNumber) {
      wx.showToast({
        title: '请填写联系电话',
        icon: 'none',
        duration: 3000
      })
    } else if (!params.province) {
      wx.showToast({
        title: '请选择所在区域',
        icon: 'none',
        duration: 3000
      })
    } else if (!params.detailAddress) {
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none',
        duration: 3000
      })
    } else {
      app.reqFun.requestJson('POST',newAddress,params,(res)=>{
        if(res.data.success === 1) {
          wx.showToast({
            title: '新增成功',
            icon: 'success',
            duration: 5000
          })
          wx.navigateBack({
            delta: 1
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 5000
          })
        }
      })
    }
  },
  // 更新默认地址
  updateDefaultStatus() {
    let that = this
    let sprovince = that.data.sprovince
    let scity = that.data.scity
    let sregion = that.data.sregion
    let sstreetName = that.data.sstreetName
    let defaultStatus
    if(that.data.setDefault) {
      defaultStatus = 'Y'
    } else {
      defaultStatus = 'N'
    }
    let params = {
      'city':	scity.code,
      'defaultStatus':	defaultStatus,
      'detailAddress':	that.data.detailAddress,
      'id': that.data.id,
      'memberId':	'',
      'name':	that.data.name,
      'phoneNumber': that.data.phoneNumber,
      'postCode':	'',
      'province': sprovince.code,
      'region': sregion.code,
      'street': sstreetName.code,
    }
    app.reqFun.requestJson('POST',updateDefault,params,(res)=>{
      if(res.data.success === 1) {
        wx.showToast({
          title: '设置成功',
          icon: 'success',
          duration: 5000
        })
      }
    })
  },
   // 修改地址
   updateAddress() {
    let that = this
    let defaultStatus
    let sprovince = that.data.sprovince
    let scity = that.data.scity
    let sregion = that.data.sregion
    let sstreetName = that.data.sstreetName
    
    if(that.data.setDefault) {
      defaultStatus = 'Y'
    } else {
      defaultStatus = 'N'
    }
    let params = {
      'city':	scity.code,
      'defaultStatus':	defaultStatus,
      'detailAddress':	that.data.detailAddress,
      'id': that.data.id,
      'memberId':	'',
      'name':	that.data.name,
      'phoneNumber': that.data.phoneNumber,
      'postCode':	'',
      'province': sprovince.code,
      'region': sregion.code,
      'street': sstreetName.code
    }
    app.reqFun.requestJson('POST',updateAddress,params,(res)=>{
      if(res.data.success === 1) {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 5000
        })
        wx.navigateBack({
          delta: 1
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 5000
        })
      }
    })
  },
  // 删除地址
  delAddress() {
    let url = `${deleteAddress}/${this.data.id}`
    app.reqFun.requestJson('GET',url,'',(res)=>{
      if(res.data.success === 1) {
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 5000
        })
        wx.navigateBack({
          delta: 1
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },
  selectModel(e){  //打开地区弹窗
    this.setData({
      showOtherAddr:true
    })
    let data = this.data.temporaryAddressData
    let code = this.data.sregion
    if(data) {
      this.getAddressSelectData(data.region, 'edit')
    } else if(code) {
      console.log('code', code)
      this.getAddressSelectData(code.code, 'edit')
    } else if(!this.data.showAddress) {
      this.getAddressSelectData()
    }
  },
  onCloseModel2(){  //关闭选择地址弹窗
    this.setData({showOtherAddr:false})
  },
  restSelect(e){  //重新选择
    console.log('从新', e)
    if(e.currentTarget.dataset.val==2){
      this.setData({sprovince:'',scity:'',sregion:'',sstreetName:''})
      this.getAddressSelectData()
    }else if(e.currentTarget.dataset.val==3){
      this.setData({scity:'',sregion:'',sstreetName:''})
      this.getAddressSelectData(e.currentTarget.dataset.item,true)
    }else if(e.currentTarget.dataset.val==4){
      this.setData({sregion:'',sstreetName:''})
      this.getAddressSelectData(e.currentTarget.dataset.item,true)
    }
  },
  //获取4级地址数据
  getAddressSelectData(options, whether){
    var that = this
    var parms = {parentCode:100000000000}
    var data = ""
    if(options) {
      if(whether){
        data = options
      } else {
        data = options.currentTarget.dataset.val
      }  
      parms.parentCode = data.code
      if(data.areaLevel == 2){
        that.setData({sprovince:data})
      }else if(data.areaLevel==3){
        that.setData({scity:data})
      }else if(data.areaLevel==4){
        that.setData({sregion:data})
      }else if(data.areaLevel==5){
        that.setData({sstreetName:data})
      }
    }
    app.reqFun.requestJson('get',listByParentCode,parms,(res)=>{
      if(res.data.success == 1){ 
        if(res.data.data.length > 0){
          that.setData({
            itemsAddr: res.data.data,      
          })
        } else {
          if (whether!== 'edit') {
            that.setData({
              showOtherAddr: false
            })
          }
          var temporaryAddressData = {}
          temporaryAddressData.province = that.data.sprovince
          temporaryAddressData.city = that.data.scity
          temporaryAddressData.region = that.data.sregion
          temporaryAddressData.streetName = that.data.sstreetName
          let showAddress = temporaryAddressData.province.name+temporaryAddressData.city.name+temporaryAddressData.region.name+(temporaryAddressData.streetName.name || '')
          that.setData({
            temporaryAddressData: temporaryAddressData,
            showAddress: showAddress
          })
        }
      }else{
        wx.showToast({
          title: '查询地址失败：'+res.data.msg,
          icon:'none'
        })
      }
    },true)
  },
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
